package com.cos.hospital.ui.main.adapter;

import android.content.Context;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cos.hospital.R;
import com.cos.hospital.code.Logic;
import com.cos.hospital.model.bean.PatientListBean;

import java.util.List;

/**
 * 患者管理适配器
 * Created by yby on 2018/9/10
 */
public class PatientAdapter extends BaseQuickAdapter<PatientListBean.ItemsBean, BaseViewHolder> {
    private List<PatientListBean.ItemsBean> data;

    public PatientAdapter(@Nullable List<PatientListBean.ItemsBean> data) {
        super(R.layout.item_patient, data);
        this.data = data;
    }

    @Override
    protected void convert(BaseViewHolder helper, PatientListBean.ItemsBean item) {
        Context context = helper.itemView.getContext();
        int layoutPosition = helper.getLayoutPosition();
        ImageView iv = helper.getView(R.id.iv);
        helper.setText(R.id.tv_name, item.getFldPatientName());
        helper.setText(R.id.tv_age, item.getFldAge() + "岁");
        helper.setText(R.id.tv_gender, Logic.getSex(item.getFldPatientSex()));
        helper.setVisible(R.id.iv_wechat, item.getFldRegisterType() == 0);

        TextView tv_letter = helper.getView(R.id.tv_letter);
        int section = getSectionForPosition(layoutPosition);
        //如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
        if (layoutPosition == getPositionForSection(section)) {
            tv_letter.setVisibility(View.VISIBLE);
            tv_letter.setText(item.getLetter());
        } else {
            tv_letter.setVisibility(View.GONE);
        }
        if (item.isSearchResult()) {
            helper.itemView.setBackgroundResource(R.color.search_light);
        } else {
            helper.itemView.setBackgroundResource(R.drawable.item_selector);
        }

        helper.addOnClickListener(R.id.iv_send);
        ProgressBar progressBar = helper.getView(R.id.remain_progress);
        int progress = item.getTreatmentNumber() * 100 / (item.getTreatmentTotal() == 0 ? 100 : item.getTreatmentTotal());
        progressBar.setProgress(progress);
        helper.setText(R.id.tv_num, item.getTreatmentNumber() + "/" + item.getTreatmentTotal());
    }

    /**
     * 根据position获取分类的首字母的char ascii值
     */
    private int getSectionForPosition(int position) {
        return data.get(position).getLetter().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < data.size(); i++) {
            String sortStr = data.get(i).getLetter();
            char firstChar = sortStr.charAt(0);
            if (firstChar == section) {
                return i;
            }
        }
        return -1;
    }

}
